package org.jeecg.modules.flow.temp.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.modules.basic.customer.entity.BasicCustomer;
import org.jeecg.modules.basic.customer.service.IBasicCustomerService;
import org.jeecg.modules.basic.material.entity.BasicMaterial;
import org.jeecg.modules.basic.material.service.IBasicMaterialService;
import org.jeecg.modules.basic.plant.entity.WmsSapWarehouseMap;
import org.jeecg.modules.basic.plant.service.IWmsSapWarehouseMapService;
import org.jeecg.modules.basic.print.entity.WmsDocumentTypeFields;
import org.jeecg.modules.basic.print.entity.WmsMaterialFields;
import org.jeecg.modules.basic.print.service.IWmsDocumentTypeFieldsService;
import org.jeecg.modules.basic.print.service.IWmsMaterialFieldsService;
import org.jeecg.modules.basic.warehouse.entity.WmsBasicWarehouse;
import org.jeecg.modules.basic.warehouse.entity.WmsBasicWarehouseArea;
import org.jeecg.modules.basic.warehouse.entity.WmsBasicWarehouseAreaLocation;
import org.jeecg.modules.basic.warehouse.mapper.WmsBasicWarehouseMapper;
import org.jeecg.modules.basic.warehouse.service.IWmsBasicWarehouseAreaLocationService;
import org.jeecg.modules.basic.warehouse.service.IWmsBasicWarehouseAreaService;
import org.jeecg.modules.basic.warehouse.service.IWmsBasicWarehouseService;
import org.jeecg.modules.business.doc.business.service.IWmsInReceiptMaterialService;
import org.jeecg.modules.business.doc.business.service.IWmsInReceiptService;
import org.jeecg.modules.business.doc.business.vo.WarehousingStrategyOneParamVO;
import org.jeecg.modules.business.outbound.entity.WmsOutReceiptTask;
import org.jeecg.modules.business.outbound.entity.WmsOutReceiptTaskMaterial;
import org.jeecg.modules.business.outbound.mapper.WmsOutReceiptTaskMaterialMapper;
import org.jeecg.modules.business.outbound.service.IWmsOutReceiptTaskService;
import org.jeecg.modules.business.repertory.entity.WmsRepertory;
import org.jeecg.modules.business.repertory.service.IWmsRepertoryService;
import org.jeecg.modules.business.warehouse.entity.WmsInReceiptTask;
import org.jeecg.modules.business.warehouse.entity.WmsInReceiptTaskMaterial;
import org.jeecg.modules.business.warehouse.entity.vo.WmsInReceiptTaskPage;
import org.jeecg.modules.business.warehouse.service.IWmsInReceiptTaskMaterialService;
import org.jeecg.modules.business.warehouse.service.IWmsInReceiptTaskService;
import org.jeecg.modules.dock.constant.SystemConstants;
import org.jeecg.modules.dock.enums.ReceiptsEnum;
import org.jeecg.modules.flow.sys.entity.dto.BaseFlowDto;
import org.jeecg.modules.flow.sys.service.WorkFlowService;
import org.jeecg.modules.flow.temp.entity.MaterialTaskExcel;
import org.jeecg.modules.flow.temp.entity.UpdateHiddenStatusField;
import org.jeecg.modules.flow.temp.service.CreateTaskService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/*
 * 项目名称:    wms-server-jeecg
 * 接口描述:    //
 * 创建人员:    zhaojun
 * 创建时间:    2023-12-02
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class CreateTaskServiceImpl implements CreateTaskService {

    private final IWmsSapWarehouseMapService wmsSapWarehouseMapService;
    private final IBasicMaterialService basicMaterialService;
    private final IWmsInReceiptService wmsInReceiptService;
    private final WorkFlowService workFlowService;
    private final IBasicCustomerService basicCustomerService;
    private final IWmsInReceiptTaskMaterialService wmsInReceiptTaskMaterialService;
    private final IWmsBasicWarehouseService warehouseService;
    private final IWmsBasicWarehouseAreaLocationService warehouseAreaLocationService;
    private final IWmsRepertoryService repertoryService;


    private static final String WAREHOUSE_DOCUMENT_IN_CODE = "rkrw_rule";
    private static final String WAREHOUSE_PARAM = "{\"prefix\":\"RKRW\"}";
    private static final String SAP_REQUEST_PERSON = "仓管员";

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> importExcel(HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(0);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<WmsRepertory> list = ExcelImportUtil.importExcel(file.getInputStream(), WmsRepertory.class, params);


                List<WmsRepertory> addList = new ArrayList<>();
                List<WmsRepertory> updateList = new ArrayList<>();

                int addCount = 0;
                int updateCount = 0;
                List<String> batchCodes = new ArrayList<>();
                WmsRepertory wmsRepertory = null;

                Map<String, String> basicUnitMap = new HashMap<>();


                Map<String, BasicMaterial> basicMaterialMap = new HashMap<>();
                List<String> materialIds = list.stream().map(t -> t.getMaterialCode()).distinct().collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(materialIds)) {
                    List<BasicMaterial> materialIdsList = basicMaterialService.list(new LambdaQueryWrapper<BasicMaterial>().in(BasicMaterial::getCode, materialIds));
                    if (CollectionUtil.isNotEmpty(materialIdsList)) {
                        basicMaterialMap = materialIdsList.stream().collect(Collectors.toMap(t -> t.getCode(), a -> a));
//                        basicUnitMap = materialIdsList.stream().collect(Collectors.toMap(t->t.getId(),a->a.getInventoryUnitId()));
                    }
                }

                // 仓库
                Map<String, WmsBasicWarehouse> warehouseMap = new HashMap<>();
                List<String> warehouseIds = list.stream().map(t -> t.getWmsBasicWarehouseId()).distinct().collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(warehouseIds)) {
                    List<WmsBasicWarehouse> warehouseList = warehouseService
                            .list(new LambdaQueryWrapper<WmsBasicWarehouse>().in(WmsBasicWarehouse::getName, warehouseIds)
                                    .eq(WmsBasicWarehouse::getDelFlag, "0"));

                    if (CollectionUtil.isNotEmpty(warehouseList)) {
                        warehouseMap = warehouseList.stream().collect(Collectors.toMap(t -> t.getName(), a -> a));
                    }
                }

                // 库区
                Map<String, WmsBasicWarehouseArea> warehouseAreaMap = new HashMap<>();
                List<String> warehouseAreaIds = list.stream().map(t -> t.getWmsBasicWarehouseAreaId()).distinct().collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(warehouseAreaIds)) {
                    List<WmsBasicWarehouseArea> warehouseAreaList = warehouseAreaService
                            .list(new LambdaQueryWrapper<WmsBasicWarehouseArea>().in(WmsBasicWarehouseArea::getName, warehouseAreaIds));

                    if (CollectionUtil.isNotEmpty(warehouseAreaList)) {
                        warehouseAreaMap = warehouseAreaList.stream().collect(Collectors.toMap(t -> t.getName(), a -> a));
                    }
                }

                // 库位
                Map<String, WmsBasicWarehouseAreaLocation> warehouseAreaLocationMap = new HashMap<>();
                List<String> warehouseAreaLocationIds = list.stream().map(t -> t.getWmsBasicWarehouseAreaLocationId()).distinct().collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(warehouseAreaLocationIds)) {
                    List<WmsBasicWarehouseAreaLocation> warehouseAreaLocationList = warehouseAreaLocationService
                            .list(new LambdaQueryWrapper<WmsBasicWarehouseAreaLocation>().in(WmsBasicWarehouseAreaLocation::getName, warehouseAreaLocationIds));

                    if (CollectionUtil.isNotEmpty(warehouseAreaLocationList)) {
                        warehouseAreaLocationMap = warehouseAreaLocationList.stream().collect(Collectors.toMap(t -> t.getName(), a -> a));
                    }
                }


                Map<String, BasicCustomer> basicCustomerMap = new HashMap<>();
                List<String> basicSupplierIds = list.stream().map(t -> t.getWmsBasicSupplierId()).distinct().collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(basicSupplierIds)) {
                    List<BasicCustomer> basicCustomerList = basicCustomerService
                            .list(new LambdaQueryWrapper<BasicCustomer>().in(BasicCustomer::getCode, basicSupplierIds)
                                    .eq(BasicCustomer::getKind, "1"));
                    if (CollectionUtil.isNotEmpty(basicCustomerList)) {
                        basicCustomerMap = basicCustomerList.stream().collect(Collectors.toMap(t -> t.getCode(), a -> a));
                    }
                }

                for (int i = 0; i < list.size(); i++) {
                    if(ObjectUtil.compare(list.get(i).getStockQuantity(),new BigDecimal("0")) == 0){
                        continue;
                    }
                    wmsRepertory = list.get(i);

                    // 物料
                    if (ObjectUtil.isNotNull(basicUnitMap.get(wmsRepertory.getMaterialId()))) {
                        String unitId = basicUnitMap.get(wmsRepertory.getMaterialId());
                        wmsRepertory.setWmsBasicUnitId(unitId);
                    }

                    // 仓库
                    if (ObjectUtil.isNotNull(warehouseMap.get(wmsRepertory.getWmsBasicWarehouseId()))) {
                        WmsBasicWarehouse wmsBasicWarehouse = warehouseMap.get(wmsRepertory.getWmsBasicWarehouseId());
                        wmsRepertory.setWmsBasicWarehouseId(wmsBasicWarehouse.getId());
                    }

                    // 库区
                    if (ObjectUtil.isNotNull(warehouseAreaMap.get(wmsRepertory.getWmsBasicWarehouseAreaId()))) {
                        WmsBasicWarehouseArea warehouseArea = warehouseAreaMap.get(wmsRepertory.getWmsBasicWarehouseAreaId());
                        wmsRepertory.setWmsBasicWarehouseAreaId(warehouseArea.getId());
                    }

                    // 库位
                    if (ObjectUtil.isNotNull(warehouseAreaLocationMap.get(wmsRepertory.getWmsBasicWarehouseAreaLocationId()))) {
                        WmsBasicWarehouseAreaLocation wmsBasicWarehouseAreaLocation = warehouseAreaLocationMap.get(wmsRepertory.getWmsBasicWarehouseAreaLocationId());
                        wmsRepertory.setWmsBasicWarehouseAreaLocationId(wmsBasicWarehouseAreaLocation.getId());
                    }

                    if (ObjectUtil.isNotNull(wmsRepertory.getStockQuantity())) {
                        if (ObjectUtil.isNotNull(wmsRepertory.getStockQuantity())) {
                            wmsRepertory.setUsableQuantity(wmsRepertory.getStockQuantity());
                        }
                    }
                    // 物料
                    if (ObjectUtil.isNotNull(basicMaterialMap.get(wmsRepertory.getMaterialCode()))) {
                        BasicMaterial basicMaterial = basicMaterialMap.get(wmsRepertory.getMaterialCode());
                        wmsRepertory.setMaterialId(basicMaterial.getId());
                        wmsRepertory.setMaterialName(basicMaterial.getName());
                        wmsRepertory.setMaterialCode(basicMaterial.getCode());
                    }

                    // 物料
                    if (ObjectUtil.isNotNull(basicCustomerMap.get(wmsRepertory.getWmsBasicSupplierId()))) {
                        BasicCustomer basicCustomer = basicCustomerMap.get(wmsRepertory.getWmsBasicSupplierId());
                        wmsRepertory.setWmsBasicSupplierId(basicCustomer.getId());
                    }

                    // 根据编码查询
                    if (StringUtils.isNotBlank(wmsRepertory.getBatchCode())) {
                        List<WmsRepertory> wmsRepertorys = repertoryService.list(new LambdaQueryWrapper<WmsRepertory>().eq(WmsRepertory::getBatchCode, wmsRepertory.getBatchCode()));
                        if (ObjectUtil.isNotEmpty(wmsRepertorys)) {
                            WmsRepertory wmsRepertory1 = wmsRepertorys.get(0);
                            if (wmsRepertorys.size() > 1) {
                                batchCodes.add(wmsRepertory.getBatchCode());
                            }
                            BeanUtils.copyProperties(wmsRepertory, wmsRepertory1, "id");
                            updateList.add(wmsRepertory1);
                        } else {
                            addList.add(wmsRepertory);
                        }

                    }
                    if (CollectionUtil.isNotEmpty(addList) && i % 1000 == 0) {
                        repertoryService.saveBatch(addList);
                        addCount += addList.size();
                        addList = new ArrayList<>();
                    }
                    if (CollectionUtil.isNotEmpty(updateList) && i % 1000 == 0) {
                        repertoryService.updateBatchById(updateList);
                        updateCount += updateList.size();
                        updateList = new ArrayList<>();
                    }
                }
                if (CollectionUtil.isNotEmpty(addList)) {
                    addCount += addList.size();
                    repertoryService.saveBatch(addList);
                }
                List<String> collects = new ArrayList<>();
                if (CollectionUtil.isNotEmpty(updateList)) {
                    updateCount += updateList.size();
                    collects = updateList.stream().map(WmsRepertory::getBatchCode).collect(Collectors.toList());
                    repertoryService.updateBatchById(updateList);
                }
                log.info("导入共计：" + list.size() + ",更新：" + updateCount + "更新的批次号为: " + collects + ",新增：" + addCount);
                log.info("重复的编码：" + (CollectionUtil.isNotEmpty(batchCodes) ? batchCodes.stream().collect(Collectors.joining(",")) : ""));
                return org.jeecg.common.api.vo.Result.OK("文件导入成功！数据行数：" + list.size());

            } catch (Exception e) {
                String msg = e.getMessage();
                log.error(msg, e);
                if (msg != null && msg.indexOf("Duplicate entry") >= 0) {
                    throw new JeecgBootException("文件导入失败:有重复数据！");
                } else {
                    throw new JeecgBootException("文件导入失败:" + e.getMessage());
                }
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    private final IWmsDocumentTypeFieldsService wmsDocumentTypeFieldsService;

    private final IWmsMaterialFieldsService wmsMaterialFieldsService;

    @Override
    public Map updateHiddenStatusField(UpdateHiddenStatusField updateHiddenStatusField) {
        Map map = new HashMap();
        List<String> unfindDocumentTypeFields = new ArrayList<>();

        List<String> unfindMaterialFields = new ArrayList<>();

        List<WmsDocumentTypeFields> documentTypeFieldsAll = wmsDocumentTypeFieldsService.list(new LambdaQueryWrapper<WmsDocumentTypeFields>().eq(WmsDocumentTypeFields::getPrintConfigId, updateHiddenStatusField.getId()));
        documentTypeFieldsAll.stream().forEach(t -> t.setHidden(0));
        List<String> documentTypeFieldsSome = Arrays.stream(updateHiddenStatusField.getDocumentTypeFields().split("、")).collect(Collectors.toList());
        for (String one : documentTypeFieldsSome) {
            Optional<WmsDocumentTypeFields> first = documentTypeFieldsAll.stream().filter(t -> {
                if (StringUtils.isNotBlank(t.getName()) && t.getName().equals(one)) {
                    return true;
                }
                return false;
            }).findFirst();
            if (first.isPresent()) {
                first.get().setHidden(1);
            } else {
                unfindDocumentTypeFields.add(one);
            }
        }
        wmsDocumentTypeFieldsService.updateBatchById(documentTypeFieldsAll);

        map.put("unfindDocumentTypeFields", unfindDocumentTypeFields.stream().collect(Collectors.joining("、")));

        List<WmsMaterialFields> materialFieldsAll = wmsMaterialFieldsService.list(new LambdaQueryWrapper<WmsMaterialFields>().eq(WmsMaterialFields::getPrintConfigId, updateHiddenStatusField.getId()));
        materialFieldsAll.stream().forEach(t -> t.setHidden(0));
        List<String> materialFieldsSome = Arrays.stream(updateHiddenStatusField.getMaterialFields().split("、")).collect(Collectors.toList());
        for (String one : materialFieldsSome) {
            Optional<WmsMaterialFields> first = materialFieldsAll.stream().filter(t -> {
                if (StringUtils.isNotBlank(t.getName()) && t.getName().equals(one)) {
                    return true;
                }
                return false;
            }).findFirst();
            if (first.isPresent()) {
                first.get().setHidden(1);
            } else {
                unfindMaterialFields.add(one);
            }
        }
        wmsMaterialFieldsService.updateBatchById(materialFieldsAll);
        map.put("unfindMaterialFields", unfindMaterialFields.stream().collect(Collectors.joining("、")));

        return map;
    }

    private final WmsOutReceiptTaskMaterialMapper outReceiptTaskMaterialMapper;

    private final IWmsRepertoryService wmsRepertoryService;

    private final IBasicMaterialService materialService;

    private final IWmsInReceiptTaskService wmsInReceiptTaskService;

    private final IWmsInReceiptMaterialService wmsInReceiptMaterialService;

    private final WmsBasicWarehouseMapper wmsBasicWarehouseMapper;


    // 目前我们搞的都是原卷
    @Override
    public void useOutOrderMaterialAddStock(String taskId,String outHouse) {
        String wmsBasicWarehouseId;
        if(StringUtils.isNotBlank(outHouse)){
            WmsBasicWarehouse wmsBasicWarehouse = wmsBasicWarehouseMapper.selectOne(new LambdaQueryWrapper<WmsBasicWarehouse>().eq(WmsBasicWarehouse::getCode, outHouse));
            wmsBasicWarehouseId = wmsBasicWarehouse.getId();
        } else {
            wmsBasicWarehouseId = "";
        }

        LambdaQueryWrapper<WmsOutReceiptTaskMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(taskId)){
            lambdaQueryWrapper.eq(WmsOutReceiptTaskMaterial::getWmsOutReceiptTaskId,taskId);
        }
        // 查询所有未完成的出库任务明细
        List<WmsOutReceiptTaskMaterial> wmsOutReceiptTaskMaterials = outReceiptTaskMaterialMapper.selectList(lambdaQueryWrapper);
        List<WmsOutReceiptTaskMaterial> outReceiptTaskMaterials = wmsOutReceiptTaskMaterials.stream()
                .filter(t -> ObjectUtil.compare(t.getPlanQuantity(), t.getHasOutboundQuantity()) > 0).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(outReceiptTaskMaterials)) {

            List<String> batchCodes = outReceiptTaskMaterials.stream().map(t -> t.getBatchCode()).distinct().collect(Collectors.toList());

            // 存在的即时库存
            List<WmsRepertory> hasRepertoryList = wmsRepertoryService.list(new LambdaQueryWrapper<WmsRepertory>()
                    .in(WmsRepertory::getBatchCode, batchCodes));
            String hasBatchCodes = hasRepertoryList.stream().map(t -> t.getBatchCode()).distinct().collect(Collectors.joining(","));

            List<WmsOutReceiptTaskMaterial> notExistTaskMaterial = outReceiptTaskMaterials.stream()
                    .filter(t -> !hasBatchCodes.contains(t.getBatchCode())).collect(Collectors.toList());

            if (CollectionUtil.isNotEmpty(notExistTaskMaterial)) {
                List<WmsRepertory> list = new ArrayList<>();
                notExistTaskMaterial.stream().forEach(t -> {
                    WmsRepertory wmsRepertory = new WmsRepertory();
                    BasicMaterial basicMateril = materialService.getById(t.getWmsBasicMaterialId());
                    if (ObjectUtil.isNotEmpty(basicMateril)) {
                        wmsRepertory.setMaterialName(basicMateril.getName());
                    }
                    wmsRepertory.setMaterialCode(t.getMaterialCode());
                    wmsRepertory.setMaterialId(t.getWmsBasicMaterialId());
                    wmsRepertory.setBatchCode(t.getBatchCode());
                    if(StringUtils.isNotBlank(wmsBasicWarehouseId)){
                        wmsRepertory.setWmsBasicWarehouseId(wmsBasicWarehouseId);
                    }else{
                        wmsRepertory.setWmsBasicWarehouseId(t.getWmsBasicWarehouseId());
                        wmsRepertory.setWmsBasicWarehouseAreaId(t.getWmsBasicWarehouseAreaId());
                        wmsRepertory.setWmsBasicWarehouseAreaLocationId(t.getWmsBasicWarehouseAreaLocationId());
                    }

                    wmsRepertory.setStockQuantity(t.getPlanQuantity());
                    wmsRepertory.setUsableQuantity(t.getPlanQuantity());
                    wmsRepertory.setWmsBasicUnitId(t.getWmsBasicUnitId());
                    wmsRepertory.setMeasuredWeight(t.getPlanQuantity());
                    wmsRepertory.setGrossWeight(t.getPlanQuantity());
                    wmsRepertory.setOriginalWeight(t.getPlanQuantity());
                    wmsRepertory.setNewestInboundTime(new Date());
                    wmsRepertory.setWarehouseDate(new Date());
                    wmsRepertory.setSaleOrderCode(t.getSaleOrderNumber());
                    wmsRepertory.setSaleOrderLineCode(t.getSaleOrderLineNumber());
                    wmsRepertory.setProductType(t.getProductType());
                    wmsRepertory.setProductModel(t.getProductModel());
                    list.add(wmsRepertory);
                });
                wmsRepertoryService.saveBatch(list);
            }

            List<String> inMaterialBatchCodes = notExistTaskMaterial.stream().map(t -> t.getBatchCode()).distinct().collect(Collectors.toList());
            List<WmsInReceiptTaskMaterial> inReceiptTaskMaterials = wmsInReceiptTaskMaterialService.list(
                    new LambdaQueryWrapper<WmsInReceiptTaskMaterial>().in(WmsInReceiptTaskMaterial::getBatchCode, inMaterialBatchCodes)
            );
            List<String> inReceiptTaskIds = inReceiptTaskMaterials.stream().map(t -> t.getWmsInReceiptTaskId())
                    .distinct().collect(Collectors.toList());
            String validBatchCode = "";
            for (String one : inMaterialBatchCodes) {
                validBatchCode += "'" + one + "',";
            }
            List<WmsInReceiptTask> list = wmsInReceiptTaskService.list(
                    new LambdaQueryWrapper<WmsInReceiptTask>().in(WmsInReceiptTask::getId, inReceiptTaskIds)
            );
            String collect = list.stream().map(t -> t.getDocumentCode()).collect(Collectors.joining(","));
            System.out.println("====================验证批次号：" + validBatchCode);
            System.out.println("====================总数：" + list.size());
            System.out.println("====================单据：" + collect);
        }
    }

    private final WmsBasicWarehouseMapper warehouseMapper;

    private final IWmsBasicWarehouseAreaService warehouseAreaService;

    private final IWmsBasicWarehouseAreaLocationService wmsBasicWarehouseAreaLocationService;

    @Override
    public void changeWarehouse(String id) {
        WmsBasicWarehouse wmsBasicWarehouse = warehouseMapper.selectById(id);
        String[] split = wmsBasicWarehouse.getCode().split("-");
        String ckCode = split[1];
        List<WmsBasicWarehouseArea> wmsBasicWarehouseAreas = warehouseAreaService.list(
                new LambdaQueryWrapper<WmsBasicWarehouseArea>()
                        .in(WmsBasicWarehouseArea::getWmsBasicWarehouseId, id));
        List<WmsBasicWarehouseArea> listArea = new ArrayList<>();
        List<WmsBasicWarehouseAreaLocation> listAreaLocation = new ArrayList<>();

        wmsBasicWarehouseAreas.stream().forEach(t -> {
            String sq = t.getCode().replace("SQ", ckCode);
            t.setCode(sq);
            listArea.add(t);
            List<WmsBasicWarehouseAreaLocation> wmsBasicWarehouseAreaLocations = wmsBasicWarehouseAreaLocationService.list(new LambdaQueryWrapper<WmsBasicWarehouseAreaLocation>()
                    .in(WmsBasicWarehouseAreaLocation::getWmsBasicWarehouseAreaId, t.getId()));
            if (CollectionUtil.isNotEmpty(wmsBasicWarehouseAreaLocations)) {
                wmsBasicWarehouseAreaLocations.stream().forEach(a -> {
                    String sq1 = a.getCode().replace("SQ", ckCode);
                    a.setCode(sq1);
                    listAreaLocation.add(a);
                });
            }
        });

        if (CollectionUtil.isNotEmpty(listArea)) {
            warehouseAreaService.updateBatchById(listArea);
        }

        if (CollectionUtil.isNotEmpty(listAreaLocation)) {
            wmsBasicWarehouseAreaLocationService.updateBatchById(listAreaLocation);
        }

    }

    /**
     * 创建单据
     *
     * @param materialTaskExcels
     */
    public void createTask(List<MaterialTaskExcel> materialTaskExcels, List<String> errorMessages) {
        if (CollectionUtil.isNotEmpty(materialTaskExcels)) {
            String location = materialTaskExcels.get(0).getStoreCode();
            String saleOrderNumber = materialTaskExcels.get(0).getSaleOrderNumber();
            //匹配配置仓库
//            List<WmsSapWarehouseMap> sapWarehouseMaps = wmsSapWarehouseMapService.list(
//                    new LambdaQueryWrapper<WmsSapWarehouseMap>()
//                            .eq(WmsSapWarehouseMap::getSapLocation, location)
//                            .eq(WmsSapWarehouseMap::getState, "1"));
//            if (ObjectUtil.isNotEmpty(sapWarehouseMaps)) {
            List<WmsInReceiptTaskMaterial> inMateriallist = new ArrayList<>();
            for (MaterialTaskExcel dto : materialTaskExcels) {
                WmsInReceiptTaskMaterial material = new WmsInReceiptTaskMaterial();
                WarehousingStrategyOneParamVO vo = new WarehousingStrategyOneParamVO();
                // 给入库单物料信息赋值
                material.setOriginalSystemNumber(dto.getSaleOrderNumber());
                material.setOriginalSystemLineNumber(dto.getSaleOrderLineNumber());
                material.setSaleOrderNumber(dto.getSaleOrderNumber());
                material.setSaleOrderLineNumber(dto.getSaleOrderLineNumber());
                material.setBatchCode(dto.getBatchCode());
                material.setSteelCoilNumber(dto.getSteelCoilNumber());
                if (dto.getMaterialName().equals("铁心") || dto.getMaterialName().equals("铁心柱")) {
                    material.setPlanQuantity(BigDecimal.ONE);
                    material.setWmsBasicUnitId("1730449614705307650");
                }
                if (dto.getMaterialName().equals("定尺硅钢")) {
                    material.setPlanQuantity(dto.getPlanQuantity());
                    if (dto.getSapStatus().equals("已过账")) {
                        material.setPlanQuantity(dto.getMeasuredWeight());
                    }
                    material.setWmsBasicUnitId("1727865673345593347");
                }
//                    // 辅数量按照产品要求默认为1
//                    material.setAssistQuantity(BigDecimal.ONE);
//                    BasicUnit unit = iBasicUnitService.getOne(new LambdaQueryWrapper<BasicUnit>()
//                            .eq(BasicUnit::getName, dto.getUnit()));
//                    if (ObjectUtil.isNotEmpty(unit)) {
//                        material.setUnitAssistId(unit.getId());
//                    }
                // 根据物料code查询物料信息
                List<BasicMaterial> basicMaterial = basicMaterialService.list(new LambdaQueryWrapper<BasicMaterial>().eq(BasicMaterial::getCode, dto.getMaterialCode()));
                if (CollectionUtil.isEmpty(basicMaterial)) {
                    errorMessages.add(String.format("========销售订单：%s=====无法查到物料%s", saleOrderNumber, dto.getMaterialCode()));
                    continue;
                }
                // 根据仓库code查询仓库ID
                List<WmsSapWarehouseMap> wmsSapWarehouseMaps = wmsSapWarehouseMapService.list(
                        new LambdaQueryWrapper<WmsSapWarehouseMap>().eq(WmsSapWarehouseMap::getSapLocation, dto.getStoreCode()));

                if (CollectionUtil.isNotEmpty(wmsSapWarehouseMaps)) {
                    WmsSapWarehouseMap wmsSapWarehouseMap = wmsSapWarehouseMaps.get(0);
                    if (ObjectUtil.isNotEmpty(wmsSapWarehouseMap)) {
                        vo.setWarehouseId(wmsSapWarehouseMap.getWmsBasicWarehouseId());
                    }
                } else {
                    vo.setWarehouseId(dto.getStoreCode());
                }

                if (ObjectUtil.isNotEmpty(basicMaterial)) {
                    material.setWmsBasicMaterialId(basicMaterial.get(0).getId());
                    vo.setMaterialId(basicMaterial.get(0).getId());
                }

                vo.setDocumentType(ReceiptsEnum.R29.getCode());
                inMateriallist.add(material);
            }
            if (inMateriallist.size() != materialTaskExcels.size()) {
                errorMessages.add(String.format("========销售订单：%s=====物料条数对不上，中止导入", saleOrderNumber));
                return;
            }
            WmsInReceiptTaskPage wmsInReceiptTaskPage = new WmsInReceiptTaskPage();
            wmsInReceiptTaskPage.setDocumentType(ReceiptsEnum.R29.getCode());
            wmsInReceiptTaskPage.setOwnerType("1");
            wmsInReceiptTaskPage.setOrganization("A04A01");
            wmsInReceiptTaskPage.setSysOrgCode("A04A01");
            wmsInReceiptTaskPage.setOwner("A05");
            wmsInReceiptTaskPage.setDocumentCode(FillRuleUtil.executeRule(WAREHOUSE_DOCUMENT_IN_CODE, JSON.parseObject(WAREHOUSE_PARAM)).toString());
            wmsInReceiptTaskPage.setWmsInReceiptTaskMaterialList(inMateriallist);
            wmsInReceiptTaskPage.setOriginalSystem(SystemConstants.SAP);
            wmsInReceiptTaskPage.setRequestTime(new Date());
            wmsInReceiptTaskPage.setRequestPerson(SAP_REQUEST_PERSON);
            wmsInReceiptTaskPage.setTaskDate(DateUtil.parseDate(DateUtil.now()));
            if (StringUtils.isNotBlank(materialTaskExcels.get(0).getWmsBasicSupplierId())) {
                //供应商和客商码会重复 add by dusongyao 2023-12-03
                BasicCustomer customer = basicCustomerService.getOne(
                        new LambdaQueryWrapper<BasicCustomer>()
                                .eq(BasicCustomer::getCode, materialTaskExcels.get(0).getWmsBasicSupplierId())
                                .eq(BasicCustomer::getKind, "1"));
                String supplierId = ObjectUtil.isEmpty(customer) ? "" : customer.getId();
                wmsInReceiptTaskPage.setWmsBasicSupplierId(supplierId);
            }
            BaseFlowDto baseFlowDto = new BaseFlowDto();
            baseFlowDto.setBusinessType(ReceiptsEnum.R29.getType());
            baseFlowDto.setDocumentType(ReceiptsEnum.R29.getCode());
            baseFlowDto.setCode(ReceiptsEnum.R29.getRemark());
            baseFlowDto.setData(wmsInReceiptTaskPage);
            try {
                workFlowService.commit(baseFlowDto);
            } catch (Exception e) {
                log.error("手动excel导入-入库任务: {}", e.toString());
            }
//            }
//            else {
//                errorMessages.add(String.format("========销售订单：%s SAP仓库未配置 %s", saleOrderNumber, location));
//            }
        }
    }
}
